// import cronstrue from "cronstrue";
import "cronstrue/locales/zh_CN";
import { getCronSplitValue, getTrueHour } from "./Cron/utils/help";
import {
  dayPoint,
  hourPoint,
  minutePoint,
  secondPoint,
  weekPoint,
} from "./Cron/utils/constants";
import dayjs from "dayjs";

const weekZhMap = {
  "1": "星期日",
  "2": "星期一",
  "3": "星期二",
  "4": "星期三",
  "5": "星期四",
  "6": "星期五",
  "7": "星期六",
};

const getDayjsInstance = (hour: any, minute: any, second: any) => {
  let dayjsInstance = dayjs();

  if (hour) {
    dayjsInstance = dayjsInstance.set("hour", Number(hour));
  }
  if (minute) {
    dayjsInstance = dayjsInstance.set("minute", Number(minute));
  }
  if (second) {
    dayjsInstance = dayjsInstance.set("second", Number(second));
  }
  console.log(dayjsInstance.format("HH:mm:ss"), hour, "hour");
  return dayjsInstance;
};
const getDayjsFormatTemplate = (hour: any, minute: any, second: any) => {
  if (hour) {
    return "HH:mm:ss";
  }
  if (minute) {
    return "mm:ss";
  }
  if (second) {
    return "ss";
  }
  return "";
};
export const cronValueToDisplay = (cronValue = "") => {
  if (!cronValue) {
    return "--";
  }
  const cronSplitValue = getCronSplitValue(cronValue || "");

  const resArr: string[] = [];

  const dayValue = cronSplitValue[dayPoint];
  const isDayMode = dayValue != "?" && dayValue != "*";
  if (isDayMode) {
    const dayZhStr =
      "每月的" +
      dayValue
        .split(",")
        .filter((w) => w && w != "0")
        .map((w) => w + "日")
        .join("、");
    resArr.push(dayZhStr);
  }

  const weekValue = cronSplitValue[weekPoint] || "";
  const isWeekMode = weekValue != "?" && weekValue != "*";
  if (isWeekMode) {
    const weekZhStr =
      "每周的" +
      weekValue
        .split(",")
        .filter((w) => w && w != "0")
        .map((w) => {
          return weekZhMap[w];
        })
        .filter((a) => a == 0 || a == "0" || a)
        .join("、");
    resArr.push(weekZhStr);
  }

  const hour = cronSplitValue[hourPoint];
  const minute = getTrueHour(cronSplitValue[minutePoint]);
  const second = getTrueHour(cronSplitValue[secondPoint]);

  if (hour.indexOf("/") > -1) {
    // 多次执行
    const [realHour = "", mult = "0"] = hour.split("/");
    const dayjsInstance = getDayjsInstance(realHour, minute, second);

    const dayjsInstanceStr = dayjsInstance.format(
      getDayjsFormatTemplate(realHour, minute, second)
    );

    resArr.push(`每日的${dayjsInstanceStr}开始,每隔${mult}小时,执行多次`);
  } else {
    const dayjsInstance = getDayjsInstance(hour, minute, second);

    const dayjsInstanceStr = dayjsInstance.format(
      getDayjsFormatTemplate(hour, minute, second)
    );
    // 执行一次
    resArr.push(`每日的${dayjsInstanceStr}执行一次`);
  }

  return resArr.join(",");
};
